import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/login')
  },
  {
    path: '/',
    name: 'layout',
    component: () => import('@/views/layout'),
    redirect: '/users',
    children: [
      {
        path: '/users',
        component: () => import(/* webpackChunkName: "users" */ '@/views/users')
      },
      {
        path: '/roles',
        component: () =>
          import(/* webpackChunkName: "roles" */ '@/views/rights/roles')
      },
      {
        path: '/rights',
        component: () =>
          import(/* webpackChunkName: "rights" */ '@/views/rights/rights')
      },
      {
        path: '/categories',
        component: () =>
          import(
            /* webpackChunkName: "categories" */ '@/views/goods/categories'
          )
      },
      {
        path: '/goods',
        component: () =>
          import(/* webpackChunkName: "goods" */ '@/views/goods/goods')
      },
      {
        path: '/goods/add',
        component: () =>
          import(/* webpackChunkName: "goodsadd" */ '@/views/goods/goodsAdd')
      },
      {
        path: '/params',
        component: () =>
          import(/* webpackChunkName: "params" */ '@/views/goods/params')
      },
      {
        path: '/orders',
        component: () =>
          import(/* webpackChunkName: "orders" */ '@/views/orders')
      },
      {
        path: '/reports',
        component: () =>
          import(/* webpackChunkName: "reports" */ '@/views/reports')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  NProgress.start() // 开启
  const user = localStorage.getItem('HEIMA_SHOP_USER')
  if (user && to.path === '/login') next('/')
  const whiteList = ['/login']
  // 白名单中就放行
  if (whiteList.includes(to.path)) {
    next()
  } else {
    // 判断是否登录了
    if (user) {
      next()
    } else {
      next('/login?url=' + to.path) // 携带上登录成功之后要去的地方
    }
  }
})
router.afterEach((to, from) => {
  NProgress.done() // 结束
})

export default router
